package com.library.service.impl;


import com.library.common.core.domain.BaseEntity;
import com.library.common.core.text.Convert;
import com.library.domain.BoIntegralHistory;
import com.library.domain.BoMembers;
import com.library.domain.MbGoods;
import com.library.domain.MbTradingRecord;
import com.library.mapper.BoIntegralHistoryMapper;
import com.library.mapper.BoMembersMapper;
import com.library.mapper.MbGoodsMapper;
import com.library.mapper.MbTradingRecordMapper;
import com.library.service.IMbTradingRecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 商品交易记录 服务层实现
 *
 * @author null
 * @date 2020-04-23
 * @blame Android Team
 */
@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class MbTradingRecordServiceImpl implements IMbTradingRecordService {
    @Resource
    private MbTradingRecordMapper mbTradingRecordMapper;

    @Resource
    private MbGoodsMapper mbGoodsMapper;

    @Resource
    private BoMembersMapper membersMapper;

    @Resource
    private BoIntegralHistoryMapper boIntegralHistoryMapper;

    /**
     * 查询商品交易记录信息
     *
     * @param id 商品交易记录ID
     * @return 商品交易记录信息
     */
    @Override
    public MbTradingRecord selectMbTradingRecordById(Integer id) {
        return mbTradingRecordMapper.selectMbTradingRecordById(id);
    }

    /**
     * 查询商品交易记录列表
     *
     * @param mbTradingRecord 商品交易记录信息
     * @return 商品交易记录集合
     */
    @Override
    public List<MbTradingRecord> selectMbTradingRecordList(MbTradingRecord mbTradingRecord) {
        return mbTradingRecordMapper.selectMbTradingRecordList(mbTradingRecord);
    }


    /**
     * 新增商品交易记录
     *
     * @param mbTradingRecords 商品交易记录信息
     * @return 结果
     */
    @Override
    public int insertMbTradingRecords(List<MbTradingRecord> mbTradingRecords) {
        //总价格
        double sumTradePrices = sumTradePrices(mbTradingRecords);
        //商品兑换明细
        for (MbTradingRecord record : mbTradingRecords) {
            int a = insertMbTradingRecord(record);
            MbGoods mbGoods = mbGoodsMapper.selectMbGoodsById(record.getGoodsId().longValue());
            if (null == mbGoods) {
                log.error("goods is null good id is {}", record.getGoodsId());
                return -1;
            }
            BoMembers boMembers = membersMapper.selectBoMembersById(record.getMembersId().longValue());
            if (null == boMembers) {
                log.error("boMembers is null boMembers id is {}", record.getMembersId());
                return -1;
            }
            int priceNum = record.getTradePrice().intValue() * record.getTradeNum();
            //增加用户积分记录
            int b = boIntegralHistory(mbGoods.getGoodsName().concat("(").concat(record.getTradeNum().toString()).concat(")"),
                    priceNum, boMembers);
            //扣除用户积分
            int c = toDeduct(priceNum, boMembers, sumTradePrices);
            sumTradePrices = sumTradePrices - record.getTradePrice();
            //扣除商品数量
            int d = minusTheGoods(mbGoods, record.getTradeNum());
            if (a <= 0 || b <= 0 || c <= 0 || d <= 0) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
        }
        return 1;
    }

    /**
     * 减去兑换的商品
     *
     * @param mbGoods  商品实体类
     * @param tradeNum 兑换数量
     * @return
     */
    private int minusTheGoods(MbGoods mbGoods, int tradeNum) {
        if (mbGoods.getGoodsNum() < tradeNum) {
            return -3;
        }
        mbGoods.setGoodsNum(mbGoods.getGoodsNum() - tradeNum);
        return mbGoodsMapper.updateMbGoods(mbGoods);
    }

    /**
     * 扣除用户积分
     *
     * @param tradePrices 商品价格
     * @param boMembers   用户
     * @return
     */
    private int toDeduct(double tradePrices, BoMembers boMembers, double sumTradePrices) {
        //总积分大于可用积分
        if (sumTradePrices > boMembers.getAvailableIntegral()) {
            return -2;
        }
        boMembers.setAvailableIntegral((int) (boMembers.getAvailableIntegral() - tradePrices));
        return membersMapper.updateBoMembers(boMembers);
    }

    /**
     * 增加用户积分变更记录
     *
     * @param goodName    商品名称
     * @param tradePrices 积分数量
     * @param boMembers   用户
     * @return
     */
    private int boIntegralHistory(String goodName, int tradePrices, BoMembers boMembers) {
        BoIntegralHistory history = new BoIntegralHistory();
        history.setAfterAdjust(boMembers.getAvailableIntegral() - tradePrices);
        history.setBeforeAdjust(boMembers.getAvailableIntegral());
        history.setAdjustNumber(-tradePrices);
        history.setAdjustReason("兑换： " + goodName);
        history.setAdjustType("3");
        history.setMembersId(boMembers.getId().longValue());
        history.setUserId("system");
        return boIntegralHistoryMapper.insertBoIntegralHistory(history);
    }


    /**
     * 商品兑换总积分
     *
     * @param mbTradingRecords 兑换列表
     * @return
     */
    private double sumTradePrices(List<MbTradingRecord> mbTradingRecords) {
        //商品价格
        double tradePrices = 0;
        for (MbTradingRecord record : mbTradingRecords) {
            MbGoods goods = mbGoodsMapper.selectMbGoodsById(record.getGoodsId().longValue());
            record.setTradePrice(goods.getGoodsScore().doubleValue());
            tradePrices += record.getTradePrice() * record.getTradeNum();
        }
        return tradePrices;
    }

    /**
     * 新增商品交易记录
     *
     * @param mbTradingRecord 商品交易记录信息
     * @return 结果
     */
    @Override
    public int insertMbTradingRecord(MbTradingRecord mbTradingRecord) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        int goods = mbTradingRecord.getGoodsId();
        MbGoods mbGoods = mbGoodsMapper.selectMbGoodsById((long) goods);
        if (null == mbGoods) {
            return -1;
        }
        mbTradingRecord.setOrderTime(new Date());
        mbTradingRecord.setTradePrice(Double.valueOf(mbGoods.getGoodsScore()));
        mbTradingRecord.setOrderNo(simpleDateFormat.format(new Date()));
        mbTradingRecord.setTradeStatus(0);
        return mbTradingRecordMapper.insertMbTradingRecord(mbTradingRecord);
    }

    /**
     * 修改商品交易记录
     *
     * @param mbTradingRecord 商品交易记录信息
     * @return 结果
     */
    @Override
    public int updateMbTradingRecord(MbTradingRecord mbTradingRecord) {
        return mbTradingRecordMapper.updateMbTradingRecord(mbTradingRecord);
    }

    /**
     * 删除商品交易记录对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteMbTradingRecordByIds(Long[] ids) {
        for (Long id : ids) {
            MbTradingRecord record = mbTradingRecordMapper.selectMbTradingRecordById(id.intValue());
            if (null == record)
                continue;
            record.setIsDelete(BaseEntity.DELETE);
            mbTradingRecordMapper.updateMbTradingRecord(record);
        }
        return BaseEntity.DELETE;
    }

}
